package main

import (
	"fmt"
	"sync"
)

//双端队列

type Deque struct {
	data    []interface{}
	left    int
	right   int
	fixSize int
	lock    *sync.RWMutex
}

func NewDeque(cap int) *Deque {
	if cap <= 0 {
		panic("队列容量不能小于 0")
	}

	deq := new(Deque)
	deq.data = make([]interface{}, cap)
	deq.left = cap - 1
	deq.right = 0
	deq.fixSize = cap
	deq.lock = new(sync.RWMutex)
	return deq
}

// 左添加
func (deq *Deque) LeftAdd(num interface{}) {

	if deq.left == deq.right && deq.left != 0 {
		panic("overflow")
	}

	deq.lock.Lock()

	fmt.Println("left:", deq.left)
	/**
		if deq.left == 0 {
			deq.left = deq.fixSize - 1
		}
	**/

	deq.data[deq.left] = num
	deq.left = deq.left - 1

	if deq.left == -1 {
		deq.left = deq.fixSize - 1
	}

	deq.lock.Unlock()
}

// 左添加
func (deq *Deque) RightAdd(num interface{}) {
	if deq.left == deq.right && deq.right != 0 {
		panic("overflow")
	}

	deq.lock.Lock()
	fmt.Println("right:", deq.right)
	deq.data[deq.right] = num
	deq.right = deq.right + 1
	deq.lock.Unlock()
}

// 右删除
func (deq *Deque) DelLeft() interface{} {

	if deq.fixSize == deq.left {
		panic("overflow")
	}

	deq.left = deq.left + 1

	if deq.left == deq.fixSize {
		deq.left = 0
	}

	return deq.data[deq.left]
}

func (deq *Deque) DelRight() interface{} {

	if deq.left == deq.right {
		panic("overflow")
	}

	deq.right = deq.right - 1
	if deq.right == -1 {
		deq.right = deq.fixSize - 1
	}

	return deq.data[deq.right]
}

func main() {

	dep := NewDeque(10)
	fmt.Println(dep)

	dep.LeftAdd(3)
	fmt.Println(dep)

	dep.RightAdd(9)
	fmt.Println(dep)

	dep.LeftAdd(4)
	fmt.Println(dep)

	dep.LeftAdd(5)
	fmt.Println(dep)

	a1 := dep.DelLeft()
	fmt.Println(dep, a1)

	dep.LeftAdd(6)
	fmt.Println(dep)

}
